<?php

class DbMysql {
    private $dbhost; // 数据库主机
    private $dbuser; // 数据库用户名
    private $dbpass; // 数据库用户名密码
    private $dbname; // 数据库名
    private $dou_link; // 数据库连接标识
    private $prefix; // 数据库前缀
    private $charset; // 数据库编码，GBK,UTF8,gb2312
    private $pconnect; // 持久链接,1为开启,0为关闭
    private $sql; // sql执行语句
    private $result; // 执行query命令的结果资源标识
    private $error_msg; // 数据库错误提示

    private static  $_instance = array();

    // 构造函数
    /*function __construct($dbhost, $dbuser, $dbpass, $dbname = '', $prefix, $charset = 'utf8mb4', $pconnect = 1) {
        $this->dbhost = $dbhost;
        $this->dbuser = $dbuser;
        $this->dbpass = $dbpass;
        $this->dbname = $dbname;
        //$this->dbport = '3307';
        $this->prefix = $prefix;
        $this->charset = strtolower(str_replace('-', '', $charset));
        $this->pconnect = $pconnect;
        $this->connect();
    }*/

    /*public static function getInstance($config=array()) {
        $key = md5(implode(":",$config));
        if (!isset(self::$_instance[$key])) {
            self::$_instance[$key] = new DbMysql($config);
        }
        return self::$_instance[$key];
    }*/

    public static function getInstance($config)
    {
        if (!(self::$_instance instanceof DbMysql)) {
            self::$_instance = new self($config);
        }
        return self::$_instance;
    }
    function __construct($config) {
        $this->config = $config;
        $this->config['charset'] = !isset($this->config['charset']) ? 'utf8mb4' : $this->config['charset'];
        $this->connect();
        //$this->dou_link = $this->connect();
    }
    
    // 数据库连接
    function connect() {
        if (!$this->dou_link = @mysqli_connect($this->config['dbhost'], $this->config['dbuser'], $this->config['dbpass'], $this->config['dbname'], $this->config['dbport'])) {
            $this->error('Can not connect to mysql server');
            return false;
        }
        if ($this->version() > '4.1') {
            if ($this->config['charset']) {
                $this->query("SET character_set_connection=" . $this->config['charset'] . ", character_set_results=" . $this->config['charset'] .
                         ", character_set_client=binary");
            }
            if ($this->version() > '5.0.1') {
                $this->query("SET sql_mode=''");
            }
        }
        return $this->dou_link;
        
        /*if (mysqli_select_db($this->dou_link, $this->dbname) === false) {
            $this->error("NO THIS DBNAME:" . $this->dbname);
            return false;
        }*/
    }
    
    // 数据库执行语句，可执行查询添加修改删除等任何sql语句
    function query($sql) {
        $this->sql = str_replace('##_', $this->config['prefix'], $sql);
        if (mysqli_select_db($this->dou_link, $this->config['dbname']) === false) {
            $this->dou_link = $this->connect();
        }
        $query = mysqli_query($this->dou_link, $this->sql);
        return $query;
    }
    
    // 取得前一次 MySQL 操作所影响的记录行数
    function affected_rows() {
        return mysqli_affected_rows($this->dou_link);
    }
    
    // 返回结果集中一个字段的值
    function result($row = 0) {
        return @ mysqli_result($this->result, $row);
    }
    
    // 返回结果集中行的数目
    function num_rows($query) {
        return @ mysqli_num_rows($query);
    }
    
    // 返回结果集中字段的数
    function num_fields($query) {
        return mysqli_num_fields($query);
    }
    
    // 释放结果内存
    function free_result() {
        return mysqli_free_result($this->result);
    }
    
    // 返回上一步 INSERT 操作产生的 ID
    function insert_id() {
        return mysqli_insert_id($this->dou_link);
    }

    //创建IN查询条件
    function where_in($item_list, $field_name = '')
    {
        if (empty($item_list)){
            return $field_name . " IN ('') ";
        }
        else{
            if (!is_array($item_list)){
                $item_list = explode(',', $item_list);
            }
            $item_list = array_unique($item_list);
            $item_list_tmp = '';
            foreach ($item_list AS $item){
                if ($item !== '')
                {
                    $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
                }
            }
            if (empty($item_list_tmp)){
                return $field_name . " IN ('') ";
            }
            else{
                return $field_name . ' IN (' . $item_list_tmp . ') ';
            }
        }
    }
    
    // 获取下一个自增(id)值
    function auto_id($table) {
        return $this->get_one("SELECT auto_increment FROM information_schema.`TABLES` WHERE  TABLE_SCHEMA='" . $this->dbname . "' AND TABLE_NAME = '" . trim($this->table($table), '`') . "'");
    }
    
    // 从结果集中取得一行作为数字数组
    function fetch_row($query) {
        return mysqli_fetch_row($query);
    }
    
    // 从结果集中取得一行作为关联数组
    function fetch_assoc($query) {
        return mysqli_fetch_assoc($query);
    }
    
    // 从结果集取得的行生成的数组
    function fetch_array($query) {
        return mysqli_fetch_array($query);
    }
    
    // 返回 MySQL 服务器的信息
    function version() {
        if (empty($this->version)) {
            $this->version = mysqli_get_server_info($this->dou_link);
        }
        return $this->version;
    }
    
    // 关闭 MySQL 连接
    function close() {
        return mysqli_close($this->dou_link);
    }
    
    // 将指定的表名加上前缀后返回
    function table($str) {
        return ' `' . $this->config['prefix'] . $str . '` ';
    }
    
    // 查询全部
    function select_all($table) {
        return $this->query("SELECT * FROM " . $table);
    }
    
    // 判断表是否存在
    function table_exist($table) {
        if($this->num_rows($this->query("SHOW TABLES LIKE '" . trim($this->table($table), '`') . "'")) == 1)
            return true;
    }
    
    // 判断字段是否存在
    function field_exist($table, $field) {
        $sql = "SHOW COLUMNS FROM " . $this->table($table);
        $query = $this->query($sql);
        while($row = mysqli_fetch_array($query, MYSQLI_ASSOC))   {
            $array[] = $row['Field'];
        }
        
        if (in_array($field, $array))
            return true;
    }
    
    // 验证信息是否已经存在
    function value_exist($table, $field, $value, $where = '') {
        $sql = "SELECT $field FROM " . $this->table($table) . " WHERE $field = '$value'" . $where;
        $number = $this->num_rows($this->query($sql));
        
        if ($number > 0){
            return true;
        }
        return false;
    }
    
    // 条件查询
    function select($table, $columnName = "*", $condition = '', $debug = '') {
        $condition = $condition ? ' Where ' . $condition : NULL;
        if ($debug) {
            echo "SELECT $columnName FROM $table $condition";
        } else {
            $query = $this->query("SELECT $columnName FROM $table $condition");
            return $query;
        }
    }
    
    // 删除数据
    function delete($table, $condition, $url = '') {
        if ($this->query("DELETE FROM $table WHERE $condition")) {
            if (!empty($url)) {
                //$GLOBALS['dou']->dou_msg($GLOBALS['_LANG']['del_succes'], $url);
                $GLOBALS['dou']->dou_header($url);
            }
        }
    }

    // 获取一个字段的值
    function get_one($sql, $limited = false) {
        if ($limited == true) {
            $sql = trim($sql . ' LIMIT 1');
        }
        
        $res = $this->query($sql);
        if ($res !== false) {
            $row = mysqli_fetch_row($res);
            
            if ($row !== false) {
                return $row[0];
            } else {
                return '';
            }
        } else {
            return false;
        }
    }

    // 获取一行记录
    function get_row($sql, $limited = false) {
        if ($limited == true) {
            $sql = trim($sql . ' LIMIT 1');
        }
        $res = $this->query($sql);
        if ($res !== false) {
            $row = mysqli_fetch_assoc($res);
            
            if ($row !== false) {
                return $row;
            } else {
                return array();
            }
        } else {
            return array();
        }
    }

    // 获取所有记录
    function get_all($sql) {
        $result = array();
        $res = $this->query($sql);
        if($res){
            while ($row = mysqli_fetch_assoc($res)) {
                $result[] = $row;
            }
        }
        return $result;
    }

    //获取一列记录
    function get_column($sql, $field)
    {
        $result = array();
        $res = $this->query($sql);
        if($res){
            while ($row = mysqli_fetch_assoc($res)) {
                $result[] = $row;
            }
            return array_column($result, $field);
        }
        return array();
    }

    //创建insert语句
    function insert_sql($table , $arr){
        $field = '';
        $value = '';
        foreach($arr as $k=>$v){
            $field .= "`$k`".',';
            $value .= "'".$this->escape_string($v)."',";
        }
        $sql = "INSERT INTO ".$this->table($table)." (".trim($field,',').") VALUES(".trim($value,',').") ";
        return $sql;
    }
    //创建update语句
    function update_sql($table, $arr, $where){
        $field = '';
        foreach($arr as $k=>$v){
            //if($v != '') $field .= " $k='".$this->escape_string($v)."',";
            $field .= " `$k`='".$this->escape_string($v)."',";
        }
        $sql = "UPDATE ".$this->table($table)." SET ".trim($field,',')." WHERE $where ;";
        return $sql;
    }
    //创建delete语句
    function delete_sql($table, $where){
        $sql = "DELETE FROM ".$this->table($table)." WHERE $where";
        return $sql;
    }
    
    // 转义特殊字符
    function escape_string($string) {
        return mysqli_real_escape_string($this->dou_link, $string);
    }
    
    // 循环读取结果集并储存至数组
    function fetch_array_all($table, $order_by = '') {
        $order_by = $order_by ? " ORDER BY " . $order_by : '';
        $query = $this->query("SELECT * FROM " . $table . $order_by);
        while ($row = $this->fetch_assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }
    
    // 返回错误信息
    function error($msg = '') {
        $msg = $msg ? "Error: $msg" : '<b>MySQL server error report</b><br>' . $this->error_msg;
        // exit($msg);
        echo $msg."\n";
        return;
    }
    
    // 数据库导入
    function fn_execute($sql) {
        $sqls = $this->fn_split($sql);
        if (is_array($sqls)) {
            foreach ($sqls as $sql) {
                if (trim($sql) != '')
                    $this->query($sql);
            }
        } else {
            $this->query($sqls);
        }
        return true;
    }
 
    // 数据分离
    function fn_split($sql) {
        if ($this->version() > '4.1' && $this->sqlcharset)
            $sql = preg_replace("/TYPE=(InnoDB|MyISAM)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET=" . $this->sqlcharset, $sql);
        
        $sql = str_replace("\r", "\n", $sql);
        $ret = array ();
        $num = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach ($queriesarray as $query) {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            $queries = array_filter($queries);
            foreach ($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-')
                    $ret[$num] .= $query;
            }
            $num++;
        }
        return ($ret);
    }
}
?>
